<template>
  <div class="content-box-full">
    <ContainerBox>
      <template #header>
        <el-form
          @keyup.enter.native="handleSearch"
          ref="searchFormRef"
          :model="searchForm"
          label-width="auto"
          inline
        >
          <el-form-item label="食堂编号：" prop="code">
            <el-input v-model.number="searchForm.code" type="text" autocomplete="off" />
          </el-form-item>
          <el-form-item label="食堂名称：" prop="name">
            <el-input v-model.number="searchForm.name" type="text" autocomplete="off" />
          </el-form-item>
          <el-form-item>
            <el-button
              v-permission="'hire:sysArea:list'"
              :disabled="isLoading"
              v-prevent-reclick
              type="primary"
              @click="handleSearch"
              >查询
            </el-button>
            <!--            <el-button :disabled="isLoading" @click="handleAdd" v-prevent-reclick>新增</el-button>-->
          </el-form-item>
        </el-form>
      </template>
      <template #default>
        <el-tabs style="height: 100%" type="border-card">
          <el-tab-pane style="height: 100%" label="食堂组织">
            <el-tree
              class="hx-scroll tree-box"
              style="height: 100%; overflow-y: auto"
              :data="canteenTreeData"
              node-key="id"
              ref="canteenTreeRef"
              :default-expand-all="true"
              :highlight-current="true"
              :props="{ children: 'treeNode', label: 'name' }"
              :expand-on-click-node="false"
              :empty-text="isLoading ? '加载中...' : '暂无数据'"
              :filter-node-method="filterTreeNode"
            >
              <template #default="{ node, data }">
                <span class="custom-tree-node">
                  <span>{{ `${data.code}-${node.label}` }}</span>
                  <span class="icon-box">
                    <el-tooltip
                      v-if="savePermission"
                      effect="light"
                      placement="top"
                      :content="'新增'"
                    >
                      <el-icon @click.stop="handleAdd(data)"><Plus /></el-icon>
                    </el-tooltip>
                    <el-tooltip
                      v-if="updatePermission"
                      effect="light"
                      placement="top"
                      :content="'编辑'"
                    >
                      <el-icon @click.stop="handleEdit(data)" style="margin-left: 10px"
                        ><Edit
                      /></el-icon>
                    </el-tooltip>
                    <el-tooltip
                      v-if="deletePermission"
                      effect="light"
                      placement="top"
                      :content="'删除'"
                    >
                      <el-icon @click.stop="handleDelete(node, data)" style="margin-left: 10px"
                        ><Delete
                      /></el-icon>
                    </el-tooltip>
                  </span>
                </span>
              </template>
            </el-tree>
          </el-tab-pane>
        </el-tabs>
      </template>
    </ContainerBox>
    <el-dialog
      lock-scroll
      top="10vh"
      class="common-el-dialog"
      v-model="showDialog"
      :title="dialogType === 'add' ? '新增食堂' : '编辑食堂'"
      width="600"
      @close="handleClose"
    >
      <el-form
        ref="dataFormRef"
        :model="dataForm"
        :rules="dataRules"
        label-width="100px"
        status-icon
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="食堂编号:" prop="code">
              <el-input v-model="dataForm.code" type="text" autocomplete="off" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="食堂名称:" prop="name">
              <el-input v-model="dataForm.name" type="text" autocomplete="off" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="承包公司:" prop="company">
              <el-input v-model="dataForm.company" type="text" autocomplete="off" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人:" prop="leader">
              <el-input v-model="dataForm.leader" type="text" autocomplete="off" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系电话:" prop="phone">
              <el-input v-model="dataForm.phone" type="text" autocomplete="off" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序:" prop="reorder">
              <el-input-number
                v-model="dataForm.reorder"
                controls-position="right"
                :min="0"
                style="width: 100%"
              ></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注:" prop="remark">
          <el-input resize="none" :rows="2" v-model="dataForm.remark" type="textarea"></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showDialog = false">取消</el-button>
          <el-button type="primary" v-prevent-reclick @click="handleFormSubmit"> 确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import ContainerBox from '@/components/base/ContainerBox.vue'
import { ref, computed, onMounted, nextTick } from 'vue'
import { useUserStore } from '@/stores/userInfo.js'
import canteenManageApi from '@/api/canteenManageApi.js'
import message from '@/utils/elMessage.js'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'

const userStore = useUserStore()

const permissions = computed(() => userStore.permissions || [])

const deletePermission = computed(() => permissions.value.includes('hire:sysArea:delete'))

const updatePermission = computed(() => permissions.value.includes('hire:sysArea:update'))

const savePermission = computed(() => permissions.value.includes('hire:sysArea:save'))

onMounted(() => {
  fetchTreeData()
})

const searchFormRef = ref(null)
const searchForm = ref({
  code: '',
  name: '',
})
const filterAreaTree = ref([])

//查询 》 过滤
function handleSearch() {
  const params = {
    code: searchForm.value.code,
    name: searchForm.value.name,
  }
  //查询条件为空 直接查询list
  if (params.code === '' && params.name === '') {
    fetchTreeData()
    return
  }
  canteenManageApi.searchAreaTree(params).then((res) => {
    if (res.code === 0) {
      filterAreaTree.value = res.AreaCodes || []
      nextTick(() => {
        canteenTreeRef.value.filter()
      })
    }
  })
}

function filterTreeNode(value, data) {
  return filterAreaTree.value.includes(data.id)
  // if (filterAreaTree.value.length) {
  //   return filterAreaTree.value.includes(data.id);
  // } else {
  //   return true
  // }
}

//食堂组织
const isLoading = ref(false)
const canteenTreeRef = ref(null)
const canteenTreeData = ref([])
const currentTreeNode = ref(null)

function fetchTreeData() {
  isLoading.value = true
  //每次刷新食堂组织 清空查询条件
  searchFormRef.value.resetFields()
  canteenManageApi
    .getAreaTree()
    .then((res) => {
      if (res.code === 0) {
        canteenTreeData.value = res.areaTree || []
      } else {
        message.warning(res.msg)
      }
    })
    .finally(() => {
      isLoading.value = false
    })
}

// 新增食堂相关
const showDialog = ref(false)
const dialogType = ref('add')
const dataFormRef = ref(null)
const dataForm = ref({
  code: '',
  name: '',
  company: '', //承包公司
  leader: '', //负责人
  phone: '', //联系电话
  reorder: 0,
  remark: '',
})
const dataRules = ref({
  code: [
    { required: true, message: '食堂编号不可以为空', trigger: 'blur' },
    {
      required: true,
      message: '食堂编号不可以为空',
      trigger: 'change',
    },
  ],
  name: [
    { required: true, message: '食堂名称不可以为空', trigger: 'blur' },
    {
      required: true,
      message: '食堂名称不可以为空',
      trigger: 'change',
    },
  ],
})

//新增
function handleAdd(data) {
  currentTreeNode.value = data
  dialogType.value = 'add'
  showDialog.value = true
}

//编辑
function handleEdit(data) {
  canteenManageApi.checkAreaInfo(data.id).then((res) => {
    if (res.code === 0) {
      currentTreeNode.value = res.sysDept || data || {}
      dialogType.value = 'edit'
      dataForm.value = {
        code: data.code || '',
        name: data.name || '',
        company: data.company || '', //承包公司
        leader: data.leader || '', //负责人
        phone: data.phone || '', //联系电话
        reorder: data.reorder || 0,
        remark: data.remark || '',
      }
      showDialog.value = true
    } else {
      message.warning(res.msg)
    }
  })
}

//删除
function handleDelete(node, data) {
  if (node.isLeaf) {
    message.confirm('确认删除该食堂？', '提示').then(() => {
      canteenManageApi.deleteAreaInfo([data.id]).then((res) => {
        if (res.code === 0) {
          canteenTreeRef.value.remove(node)
          nextTick(() => {
            message.success(res.msg)
          })
        } else {
          message.warning(res.msg)
        }
      })
    })
  } else {
    message.warning('该节点下存在子节点，不允许删除')
  }
}

function handleClose() {
  dataFormRef.value.resetFields()
  currentTreeNode.value = null
}

function handleFormSubmit() {
  dataFormRef.value.validate((bool) => {
    if (bool) {
      const isAdd = dialogType.value === 'add'
      const fetchApi = isAdd ? canteenManageApi.saveAreaInfo : canteenManageApi.updateAreaInfo
      const params = {
        code: dataForm.value.code,
        name: dataForm.value.name,
        leader: dataForm.value.leader,
        phone: dataForm.value.phone,
        remark: dataForm.value.remark,
        reorder: dataForm.value.reorder,
        company: dataForm.value.company,
        pid: isAdd ? currentTreeNode.value.id : undefined,
        id: isAdd ? undefined : currentTreeNode.value.id,
        level: currentTreeNode.value.level + 1,
      }
      fetchApi(params).then((res) => {
        if (res.code === 0) {
          message.success(res.msg)
          showDialog.value = false
          fetchTreeData()
        } else {
          message.warning(res.msg)
        }
      })
    }
  })
}
</script>

<style scoped lang="scss">
.tree-box {
  :deep(.el-tree-node__content) {
    &:hover {
      .icon-box {
        display: inline-flex;
        font-size: 16px;
      }
    }

    .custom-tree-node {
      display: flex;
      align-items: center;
    }

    .icon-box {
      display: none;
      margin-left: 10px;
    }
  }
}
</style>
